package com.huan.study.skywalking.controller;

import com.huan.study.skywalking.domain.User;
import com.huan.study.skywalking.service.UserService;
import org.apache.skywalking.apm.toolkit.trace.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;

/**
 * @author huan.fu 2020/7/5 - 22:54
 */
@RestController
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    private static final RestTemplate REST_TEMPLATE = new RestTemplate();
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("findAll")
    public Iterable<User> findAll() {
        log.info("控制层获取所有的用户信息");
        return userService.findAll();
    }

    @GetMapping("/queryGetParam")
    public Iterable<User> queryGetParam(
            @RequestParam("name") String username,
            @RequestParam("age") Integer age
    ) {
        log.info("current query param username:[{}],age:[{}]", username, age);
        return new ArrayList<>();
    }

    @GetMapping("tractAnnotation")
    public User traceAnnotation(
            @RequestParam("name") String name
    ) {
        log.info("从前端接收到的参数:[{}]", name);
        User user = trace(name);
        ActiveSpan.tag("new-tag", user.toString());
        ActiveSpan.info("输出信息");
        log.info("tractId:[{}]", TraceContext.traceId());
        return user;
    }

    @Trace(operationName = "添加自定义的方法")
    @Tags({
            @Tag(key = "从方法参数中获取值", value = "arg[0]"),
            @Tag(key = "从返回值中获取值", value = "returnedObj.name")
    })
    private User trace(String name) {
        log.info("如果此方法没有被SkyWalking收集，但是又需要被收集到，可以加上@Trace注解");
        User user = new User();
        user.setName("创建的名字");
        return user;
    }

    @GetMapping("/findAllProduct")
    public Object findAllProduct() {
        log.info("用户获取所有的商品");
        return REST_TEMPLATE.getForObject("http://localhost:9998/findAll", Object.class);
    }

    @GetMapping("tractThread")
    public String tractThread() {
        log.info("准备自己线程信息");
        new Thread(RunnableWrapper.of(() -> log.info("子线程的信息"))).start();
        return "trace thread";
    }

    @GetMapping("exception")
    public void exception() {
        log.info("测试异常");
        int i = 1 / 0;
    }

    @GetMapping("ignoreTrace")
    public String ignoreTrace() {
        return "查看博客内容，看如何忽略url不进行追踪，https://blog.csdn.net/fu_huo_1993/article/details/107188840";
    }
}
